﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RoyTools.D3Monitor.FormUI.Helper
{
    /// <summary>
    /// 计时器辅助类
    /// </summary>
    public class TimerHelper<Data>
    {
        private System.Timers.Timer timer;
        private Action before;
        private Action after;
        public Data BeforeData;
        public Data AfterData;

        public TimerHelper(int interval, Action before, Action after)
        {
            timer = new System.Timers.Timer(interval);
            this.before = before;
            this.after = after;
            timer.Elapsed += Timer_Elapsed;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public void Init()
        {
            DoBefore();
        }

        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            timer.Stop();
            DoAfter();
            timer.Start();
        }

        private void DoBefore()
        {
            before.Invoke();
        }

        private void DoAfter()
        {
            after.Invoke();
        }

        /// <summary>
        /// 开始
        /// </summary>
        public void Start()
        {
            timer.AutoReset = true;
            timer.Start();
        }

        /// <summary>
        /// 重置
        /// </summary>
        public void Reset()
        {
            Stop();
            Start();
        }

        /// <summary>
        /// 停止
        /// </summary>
        public void Stop()
        {
            timer.Stop();
        }
    }
}
